//历史订单的批量操作
import { message, Button, Popover, Popconfirm, Modal } from "antd";
import { useState } from "react";
import ActionMap from "./ActionMap";
import { checkMatchResult, checkTaobaoStore } from '../config/CheckConfig';
import { find } from 'lodash';

//默认样式
const defaultStyle = {
	margin: '0 8px 8px 0',
	height: '28px'
}

const Actions = props => {
	const { formData, selectKeys, tableList, handleOk } = props;
	const [modalName, setModalName] = useState();
	const [item, setItem] = useState({});

	//点击批量更新状态
	const handleUpdateOrderStatus = props => {
		const { scene, isModal, isCheck, isCheckTb, item = {} } = props;
		//这里需要判断是否选择了数据
		if (selectKeys.length > 0) {
			if (isCheck) {
				//需要判断是否符合条件
				const checkResult = checkMatchResult(scene, selectKeys, tableList);
				if (!checkResult) {
					return;
				}
			}
			if (isCheckTb) {
				//需要判断是否包含多个淘宝网店
				const checkResult = checkTaobaoStore(selectKeys, tableList);
				if (checkResult) {
					return;
				}
			}
			if (isModal) {
				setItem({ scene, ...item });
				setModalName(scene);
			} else {
				const items = {
					selectKeys,
					tableList
				};
				//updateOrderStatus(scene, items, afterUpdate);
			}
		} else {
			message.info("请选择售后单");
		}
	};

	//拒绝用户相关退款，退货申请的预处理函数
	const handleRefuseBuyer = (scene, title, checkTime) => {

		if (selectKeys.length == 0) {
			message.info("请选择售后单");
			return;
		}

		if (selectKeys.length > 1) {
			message.info("请选择单笔售后单");
			return;
		}

		//对于七天无理由的售后单不允许操作拒绝
		if(scene == 'RefuseBuyerReturn') {
			const obj = find(tableList, ['id', selectKeys[0]]) || {};
			if(obj.orderChannel == 1 && (obj.reason?.includes('7天无理由') || obj.reason?.includes('七天无理由'))) {
				return message.info('京东平台针对7天无理由退货的售后单不允许操作拒绝退货!')
			}
		}

		//需要判断是否符合条件
		const checkResult = checkMatchResult(scene, selectKeys, tableList);
		if (!checkResult) {
			return;
		}

		const obj = find(tableList, ['id', selectKeys[0]]);

		if ([4, 5, 8, 9, 13, 14].includes(obj.platRefundState)) {
			message.info('没有可操作的售后单，请重新勾选');
			return;
		}

		//拼多多不支持拒绝补发/换货
		if (scene == 'RefuseExchange' && obj.orderChannel == 9) {
			Modal.info({
				title: '操作提示',
				content: <div><span className="common-color9">拼多多</span>平台的<span className="common-color9">换货、补发</span>类型售后单<span className="common-color9">不支持在erp系统中操作拒绝补发/换货</span>，需要到拼多多商家后台手动点击同意或商家后台配置自动策略进行处理</div>
			})
			return;
		}

		//判断是否是淘宝订单并且满足24小时限制才能退款 
		if (checkTime) {
			if (obj.orderChannel == 8 && (Date.now() - obj.applyTime) < 86400000) {
				message.info("该售后单不满足淘宝时间限制");
				return;
			}
		}
		//唤起弹框
		handleUpdateOrderStatus({ scene: 'RefuseBuyer', isModal: true, item: { refuseType: scene, title } })
	}

	//点击买家已退货，同意退款
	const handleAgreeReturnRefund = (props) => {
		if (selectKeys.length > 0) {
			const taobaoData = tableList.filter(v => selectKeys.includes(v.id) && v.orderChannel == 8);
			if (taobaoData.length > 20) {
				return Modal.info({
					title: '注意',
					content: '淘宝退款支持一次性最多20笔'
				})
			}
			const taobaoAmount = taobaoData.reduce((pre, next) => pre + next.refundAmount, 0);
			if (taobaoAmount > 6000) {
				return Modal.info({
					title: '注意',
					content: '淘宝退款支持一次性最多6000元'
				})
			}
			const tianmaoData = tableList.filter(v => selectKeys.includes(v.id) && v.orderChannel == 18);
			if (tianmaoData.length > 30) {
				return Modal.info({
					title: '注意',
					content: '天猫退款支持一次性最多30笔'
				})
			}
			const tianmaoAmount = tianmaoData.reduce((pre, next) => pre + next.refundAmount, 0);
			if (tianmaoAmount > 10000) {
				return Modal.info({
					title: '注意',
					content: '天猫退款支持一次性最多10000元'
				})
			}
		}
		handleUpdateOrderStatus(props);
	}

	//无信息件认领
	const handelClaimNoinfo = () => {
		if (selectKeys.length == 0) {
			message.info("请选择售后单");
			return;
		}
		if (selectKeys.length > 1) {
			message.info("请勾选一个无信息件");
			return;
		}
		const obj = find(tableList, ['id', selectKeys[0]]);
		if (obj.orderList.length > 0) {
			message.info("请选择一个无信息件");
			return;
		}
		//唤起弹框
		handleUpdateOrderStatus({ scene: 'unInfoClaim', isModal: true, item: obj })
	}

	//点击物流回传
	const onConfirm = () => {
		if (selectKeys.length == 0) {
			message.info("请选择售后单");
			return;
		}
		alert('调用接口');
	}

	//点击打开处理结果弹框
	const handleOpenModal = () => {
		setModalName('HandleResultQuery');
	}

	//导出售后单
	const handleExport = async () => {
		setItem({ taskType: 2005 })
		setModalName('VertCodeExport');
	}

	//同意补发/换货, 需要限制pdd订单
	const handleAgreeExchange = () => {
		if (selectKeys.length == 0) {
			message.info("请选择售后单");
			return;
		}
		const list = tableList.filter(v => v.orderChannel == 9 && selectKeys.includes(v.id)).map(v => v.id);
		if (list.length > 0) {
			Modal.info({
				title: '操作提示',
				content: <div><span className="common-color9">拼多多</span>平台的<span className="common-color9">换货、补发</span>类型售后单<span className="common-color9">不支持在erp系统中操作同意补发/换货</span>，需要到拼多多商家后台手动点击同意或商家后台配置自动策略进行处理</div>,
			})
		} else {
			handleUpdateOrderStatus({ scene: 'AgreeExchange', isModal: true, isCheck: true });
		}
	}

	//弹框参数
	const ModalProps = {
		item,
		selectKeys,
		tableList,
		formData,
		handleOk(updateType, data) {
			setModalName();
			handleOk(updateType, data);
			//打开处理结果弹框
			if (['AgreeOnlyRefund', 'AgreeBuyerRefund', 'AgreeRefundReturned', 'AgreeExchange', 'RefuseOnlyRefund', 'RefuseBuyerReturn', 'RefuseErrorRefund', 'RefuseExchange'].includes(modalName)) {
				handleOpenModal(modalName);
			}
		},
		handleCancel() {
			setModalName();
			setItem({});
		}
	};


	//操作函数
	const actionArr = [
		{
			name: '同意仅退款', type: 'primary', action: () => handleUpdateOrderStatus({ scene: 'AgreeOnlyRefund', isModal: true, isCheck: true, isCheckTb: true }),
			desc: ['只能处理以下售后单类型的数据：', '未发货仅退款', '已发货仅退款'],
		},
		{
			name: '同意买家退货', type: 'primary', action: () => handleUpdateOrderStatus({ scene: 'AgreeBuyerRefund', isModal: true, isCheck: true }),
			desc: ['只能处理以下售后单类型的数据：', '已发货退货退款'],
		},
		{
			name: '买家已退货，同意退款', type: 'primary', action: () => handleAgreeReturnRefund({ scene: 'AgreeRefundReturned', isModal: true, isCheck: true }),
			desc: ['只能处理以下售后单类型的数据：', '已发货退货退款+买家已退货（售后状态）', '已发货退货退款+卖家已收货（售后状态）'],

		},
		{
			name: '同意补发/换货', type: 'primary', action: () => handleAgreeExchange(),
			desc: ['只能处理以下售后单类型的数据：', '补发', '换货'],
		},
		{
			name: '拒绝仅退款', action: () => handleRefuseBuyer('RefuseOnlyRefund', '拒绝仅退款', true),
			desc: ['只能处理以下售后单类型的数据：', '未发货仅退款', '已发货仅退款', '已发货退货退款', <div style={{ color: '#F03D29' }}>注：只能单笔售后单操作</div>],
		},
		{
			name: '拒绝买家退货', action: () => handleRefuseBuyer('RefuseBuyerReturn', '拒绝买家退货'),
			desc: ['只能处理以下售后单类型的数据：', '已发货退货退款', <div style={{ color: '#F03D29' }}>注：只能单笔售后单操作</div>],
		},
		{
			name: '拆包异常，拒绝退款', action: () => handleRefuseBuyer('RefuseErrorRefund', '拆包异常，拒绝退款', true),
			desc: ['只能处理以下售后单类型的数据：', '已发货退货退款+待卖家确认收货（售后状态）', <div style={{ color: '#F03D29' }}>注：只能单笔售后单操作</div>],
		},
		{
			name: '拒绝补发/换货', action: () => handleRefuseBuyer('RefuseExchange', '拒绝补发/换货'),
			desc: ['只能处理以下售后单类型的数据：', '补发', '换货', <div style={{ color: '#F03D29' }}>注：只能单笔售后单操作</div>],

		},
		{ name: '无信息件认领', action: () => handelClaimNoinfo() },
		{ name: '新建售后单', action: () => setModalName('CreateAfterSales') },
		// { name: '物流拦截', delConfirm: '是否确认要申请物流拦截??' },
		{ name: '导出', action: () => handleExport() },
	]

	const renderPopver = (arr) => {
		return arr.map((v, index) => {
			return (
				<div key={index}>{v}</div>
			)
		})
	}

	return (
		<>
			<ActionMap modalName={modalName} ModalProps={ModalProps} />
			{
				actionArr.map(v => {
					if (v.desc) {
						return (
							<Popover key={v.name} content={renderPopver(v.desc)}>
								<Button type={v.type} onClick={v.action} style={defaultStyle}>{v.name}</Button>
							</Popover>
						)
					} else {
						if (v.delConfirm) {
							return (
								<Popconfirm
									title={v.delConfirm}
									onConfirm={onConfirm}
									key={v.name}
								>
									<Button type={v.type} style={defaultStyle}>{v.name}</Button>
								</Popconfirm>
							)
						} else {
							return (
								<Button key={v.name} type={v.type} onClick={v.action} style={defaultStyle}>{v.name}</Button>
							)
						}
					}
				})
			}
		</>
	);
};
export default Actions;
